package com.zhiche.lisa.oms.util;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.oms.dao.model.Order;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * 运输各类单据编码生成器
 * <p>
 * 规则："SO/ST/SP" + 4位年份 + 2位月份 + 2位日期 + 2位小时 + 2位分钟 + 6位流水
 *
 * @author qichao
 * @create 2018-06-26
 **/
public class BillCodeGenerator {
	/**
	 * 编码中的流水号位数
	 */
	private static final String INITIAL_SN = "100000";
	public static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";

	private static DateTime strToDate(String dateTimeStr){
		DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT);
		DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
		return dateTime;
	}

	public static String dateToStr(DateTime dateTime){
		if(Objects.isNull(dateTime)){
			return null;
		}
		return dateTime.toString(STANDARD_FORMAT);
	}


	public String GenerateBillCode(String prefix) {
		DateTime dateTime = new DateTime();
		String year = String.valueOf(dateTime.getYear());
		String month = String.valueOf(dateTime.getMonthOfYear());
		String day = String.valueOf(dateTime.getDayOfMonth());
		String sn = getMaxBillCodeWithinOneMinute(prefix);
		return  prefix+year+month+day+sn;
	}

	/**
	 * 获取一分钟之内生成的最大流水号
	 * @param prefix
	 * @return
	 */
	private String getMaxBillCodeWithinOneMinute(String prefix) {

		DateTime currentTime =new DateTime();

		String dateTime = dateToStr(currentTime);

		String dateTimeOneSecondAgo = dateToStr(currentTime.minusMinutes(1));

		if(StringUtils.isEmpty(prefix)){
			throw new BaseException("无前缀！");
		}

		/**
		 * 运单编号
		 */
		if(prefix.equals("CO")){
			EntityWrapper<Order> ew = new EntityWrapper<>();
			ew.between("gmt_create",dateTimeOneSecondAgo,dateTime);
			Order order = new Order();
			int count = order.selectCount(ew);
			return String.valueOf(Integer.parseInt(INITIAL_SN)+count+1);
		}

		return null;
	}

}
